package com.yy.tech.data.logger.helper;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.yy.tech.data.context.SecretContent;
import com.yy.tech.data.logger.context.SpringContext;
import com.yy.tech.data.logger.filter.MapperPropertyFilter;
import com.yy.tech.data.logger.mapper.MapperAnnotationIntrospector;
import com.yy.tech.data.mapper.filter.FilterConfiguration;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * @author yy
 * @date 2022/5/13
 * @description: TODO
 */
public final class SecretHelperUtils {

    private static ObjectMapper mapper = help();

    public static ObjectMapper help(ObjectMapper mapper){
        SimpleBeanPropertyFilter filter = new MapperPropertyFilter();
        mapper.setAnnotationIntrospector(new MapperAnnotationIntrospector());
        Map<Class<?>,Class<?>> mixins = new HashMap<>(8);
//        mixins.put(Map.class, FilterConfiguration.MapPropertyFilterView.class);
        mixins.put(Object.class, FilterConfiguration.DesensitizeFilterView.class);
        mapper.setMixIns(mixins);
        String dateFormat = SpringContext.getEnvironment().getProperty(SecretContent.KEY_JACKSON_DATE_FORMAT,SecretContent.DATE_FORMAT);
        mapper.setDateFormat(new SimpleDateFormat(dateFormat));
        mapper.setFilterProvider(new SimpleFilterProvider().addFilter(SecretContent.MAPPER_FILTER_NAME,filter).addFilter(SecretContent.MAPPER_MAP_FILTER_NAME,filter));
        return mapper;
    }

    public static ObjectMapper help(){
        ObjectMapper mapper = new ObjectMapper();
        return help(mapper);
    }

    public static String format(Object argument) throws JsonProcessingException {
        if (null != argument){
            return mapper.writeValueAsString(argument);
        }
        return null;
    }
}
